import React, { useState } from 'react';
import styles from './index.less';
import {
  Modal,
  DatePicker,
  Space,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;
import request from '@/http';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [formObject] = Form.useForm();

  const [searchValue, setSearchValue] = React.useState('');
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 9,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '200', '500'],
    showQuickJumper: true,
  });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    // const result: any = await request.get('/admin/queryAllTeacherInfo?pageInfo.pageIndex=' + (pageValue - 1) + '&pageInfo.pageSize=' + sizeValue, {
    const result: any = await request.get(
      '/teacher/leave/queryLeaveByTeacherId',
      {
        params: {
          ...userParams,
          current: pageValue - 1,
          size: pageSize,
        },
      },
    );

    if (result && result.msg === 'Success') {
      const data = result.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        teacherId: user.teacherId, //	课程名（项目名称）
        teacherName: user.teacherName, //
        /*trainTeacherName: user.list.map( (teacher:any) => {  // 遍历教师数组
                      return  arr.concat(teacher.trainTeacherName)
                    }),*/
        leaveTheme: user.leaveTheme,
        leaveReason: user.leaveReason,
        reasonDetail: user.reasonDetail,
        stuId: user.stuId,
        stuName: user.stuName,
        stuNumber: user.stuNumber,
        gradeName: user.gradeName,
        className: user.className,
        majorName: user.majorName,
        collegeName: user.collegeName,
        leaveStatus: user.leaveStatus,
        startTime: user.startTime,
        endTime: user.endTime,
        applyTime: user.applyTime,
        courseId: user.courseId,
        transitTime: user.transitTime,
        headmaster: user.headmaster,
      }));
      const newPageObject = {
        ...pagination,
        current: pageValue,
        size: pageSize,
        total: result.total, //总条数 分页               *******************
      };
      setPagination(newPageObject);
      setDataSource(data);
      // console.log(data)
    }

    // // console.log('院系')
    // const chooseCollege: any = await request.get('/queryAllCollege')
    //     const cCollege = chooseCollege.map(
    //       (user: any) => ({
    //         key: `user_${user.collegeId}`,
    //         id: user.collegeId,
    //         collegeId: user.collegeId,
    //         collegeName: user.collegeName,
    //       }),
    //     );
    //     localStorage.setItem('collegeName', JSON.stringify(cCollege));
  };

  //院系
  const [cCollegeData, setCCollegeData] = useState<any[]>([]);
  const getCollage = async () => {
    const chooseCollege: any = await request.get('/queryAllCollege');
    // if (result.code === 'Success') {
    const cCollege = chooseCollege.map((user: any) => ({
      key: `user_${user.collegeId}`,
      id: user.collegeId,
      collegeId: user.collegeId,
      collegeName: user.collegeName,
    }));
    localStorage.setItem('collegeName', JSON.stringify(cCollege));
    let college = localStorage.getItem('collegeName');
    if (college) {
      setCCollegeData(JSON.parse(college));
    }
  };
  //专业
  const [cMajorData, setCMajorData] = useState<any[]>([]);
  const getMajor = async () => {
    const chooseMajor: any = await request.get('/queryAllMajor');
    const cMajor = chooseMajor.map((user: any) => ({
      key: `user_${user.majorId}`,
      id: user.majorId,
      majorId: user.majorId,
      majorName: user.majorName,
    }));
    localStorage.setItem('major', JSON.stringify(cMajor));
    let major = localStorage.getItem('major');
    if (major) {
      setCMajorData(JSON.parse(major));
    }
  };

  const [cGradeData, setCGradeData] = useState<any[]>([]);
  const getGrade = async () => {
    const chooseGrade: any = await request.get('/queryAllGrade');
    const cGrade = chooseGrade.map((user: any) => ({
      key: `user_${user.gradeId}`,
      id: user.gradeId,
      gradeId: user.gradeId,
      gradeName: user.gradeName,
    }));
    localStorage.setItem('gradeName', JSON.stringify(cGrade));
    let grade = localStorage.getItem('gradeName');
    if (grade) {
      setCGradeData(JSON.parse(grade));
    }
  };

  const [cClassData, setCClassData] = useState<any[]>([]);
  const getClasses = async () => {
    const chooseClass: any = await request.get('/queryAllClass');

    const cClass = chooseClass.map((user: any) => ({
      key: `user_${user.classId}`,
      id: user.classId,
      classId: user.classId,
      className: user.className,
    }));

    localStorage.setItem('classname', JSON.stringify(cClass));
    let Class = localStorage.getItem('classname');
    if (Class) {
      setCClassData(JSON.parse(Class));
    }
  };

  //搜索
  const searchOnClick = async () => {
    console.log(formObject.getFieldsValue());
    const data = await formObject.validateFields();
    var dataStr = '';
    var ds = {
      ...data,
    };
    console.log('数据');
    console.log(data);
    for (var n in ds) {
      if (dataStr != '') dataStr += '&';
      dataStr += encodeURIComponent(n) + '=' + encodeURIComponent(ds[n]);
    }
    console.log('22222222222222');
    console.log(dataStr);

    await loadDataSource(data, 1, pagination.pageSize);
  };

  //生命周期函数
  React.useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize).finally();
    getCollage();
    getMajor();
    getGrade();
    getClasses();
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  async function userEditOnClose() {
    await loadDataSource(
      formObject.getFieldsValue(),
      pagination.current,
      pagination.pageSize,
    );
  }

  //切换教师状态按钮

  //重置按钮
  const resetOnClick = () => {
    setSearchValue('');
  };

  const [state, setState] = React.useState({
    selectedRowId: [], // Check here to configure the default column
    loading: false,
  });
  const { loading, selectedRowId } = state;
  const rowSelection = {
    selectedRowId,
    onChange: onSelectChange,
  };
  function onSelectChange(selectedRowId: any) {
    console.log('selectedRowKeys changed: ', selectedRowId);
    setState({ loading: false, selectedRowId });
  }

  const hasSelected = selectedRowId.length > 0;
  const flag = hasSelected;

  return (
    <div className="pageMain">
      <div className="pageContent">
        <div className="search" style={{ width: '1400px', height: '220px' }}>
          <div className={styles.searchForm}>
            <Form layout="inline" form={formObject}>
              <Form.Item label="提交日期" name="teacherName">
                <RangePicker className="teacherInput" />
              </Form.Item>

              <Form.Item
                label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;院系"
                name="collegeName"
                initialValue=""
              >
                <Select className="teacherSelect">
                  {cCollegeData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.collegeName}
                        children={item.collegeName}
                      ></Option>
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item
                label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;专业"
                name="majorName"
                initialValue=""
              >
                <Select className="teacherSelect">
                  {cMajorData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.majorName}
                        children={item.majorName}
                      ></Option>
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item
                label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;年级"
                name="gradeName"
                initialValue=""
              >
                <Select className="teacherSelect">
                  {cGradeData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.gradeName}
                        children={item.gradeName}
                      ></Option>
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item
                label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;班级"
                name="className"
                initialValue=""
              >
                <Select className="teacherSelect">
                  {cClassData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.className}
                        children={item.className}
                      ></Option>
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item
                label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;学号"
                name="identity"
                initialValue=""
              >
                <Input className="teacherInput" placeholder="请输入..." />
              </Form.Item>

              <Form.Item label="学生姓名" name="phone" initialValue="">
                <Input
                  className="teacherInput"
                  placeholder="请输入..."
                  value={searchValue || ''}
                />
              </Form.Item>
              <Form.Item
                label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;主题"
                name="phone"
                initialValue=""
              >
                <Input
                  className="teacherInput"
                  placeholder="请输入..."
                  value={searchValue || ''}
                />
              </Form.Item>
              <Form.Item label="请假原因" name="status" initialValue="">
                <Select className="teacherSelect">
                  <Option value="">请选择...</Option>
                  <Option value="2">其它</Option>
                  <Option value="1">事假</Option>
                  <Option value="0">病假</Option>
                </Select>
              </Form.Item>
              <Form.Item label="审批状态" name="status" initialValue="">
                <Select className="teacherSelect">
                  <Option value="">请选择...</Option>
                  <Option value="1">审批中</Option>
                  <Option value="0">审批不通过</Option>
                  <Option value="2">审批通过</Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Button
                  className="searchBtn"
                  type="primary"
                  onClick={searchOnClick}
                >
                  查询
                </Button>
              </Form.Item>
              <Button onClick={resetOnClick}>重置</Button>
            </Form>
          </div>
        </div>

        <div className={styles.mainTable}>
          <Table
            rowSelection={rowSelection}
            className="ptTable"
            columns={[
              {
                title: '申请提交日期',
                dataIndex: 'applyTime',
                key: 'applyTime',
                width: 150,
              },
              {
                title: '院系',
                dataIndex: 'collegeName',
                key: 'collegeName',
                width: 150,
              },
              {
                title: '专业',
                dataIndex: 'majorName',
                key: 'majorName',
              },
              {
                title: '年级',
                dataIndex: 'gradeName',
                key: 'gradeName',
              },
              {
                title: '班级',
                dataIndex: 'className',
                key: 'className',
              },
              {
                title: '学号',
                dataIndex: 'stuNumber',
                key: 'stuNumber',
              },
              {
                title: '姓名',
                dataIndex: 'stuName',
                key: 'stuName',
              },
              {
                title: '主题',
                dataIndex: 'leaveTheme',
                key: 'leaveTheme',
              },
              {
                title: '请假原因',
                dataIndex: 'leaveReason',
                key: 'leaveReason',
                render: (leaveReason: any) =>
                  leaveReason === '0'
                    ? '病假'
                    : leaveReason === '1'
                    ? '事假'
                    : '其它',
              },
              {
                title: '原因说明',
                dataIndex: 'reasonDetail',
                key: 'reasonDetail',
              },
              {
                title: '请假开始时间',
                dataIndex: 'startTime',
                key: 'startTime',
              },
              {
                title: '请假结束时间',
                dataIndex: 'endTime',
                key: 'endTime',
              },
              {
                title: '审批状态',
                dataIndex: 'leaveStatus',
                key: 'leaveStatus',
                render: (leaveStatus: any) =>
                  leaveStatus === '0'
                    ? '审批不通过'
                    : leaveStatus === '1'
                    ? '审批中'
                    : '审批通过',
              },

              {
                title: '操作',
                key: 'action',
                align: 'center',
                width: 75,
                //  render: (row: any) => (
                //    <>
                //      <Button type="link" onClick={() => {
                //        setCurrentEditObject({
                //          ...row,
                //          isModalVisible: true,
                //        });
                //      }} style={{padding: '4px 8px'}}>
                //        编辑
                //      </Button>
                //      <Space>

                //        <Button onClick={() => {
                //          showDeleteConfirm({
                //            ...row
                //          })
                //        }} type="link">

                //          {row.status == 1 ? '停用' : '启用'}
                //        </Button>

                //      </Space>

                //    </>
                //  ),
              },
            ]}
            onChange={pageOnChange}
            dataSource={dataSource}
            pagination={pagination}
            tableLayout="fixed"
            bordered
          />
        </div>
      </div>
    </div>
  );
};
